<?php
/**
 * Created by JetBrains PhpStorm.
 * User:JAE
 * Date: 13-10-25
 * Time: 下午8:07
 * Blog:http://blog.jaekj.com
 * QQ:734708094
 * 通用数据库操作类
 * 版本:V2.4
 */
/* 数据库配置
  return array(
    'DB_CONFIG' => array(
        //数据库配置
        'DB_HOST'=>'127.0.0.1',    //服务器地址
        'DB_NAME' => 'tmp', // 数据库名
        'DB_USER' => 'root', // 用户名
        'DB_PWD' => '', // 密码
        'DB_ENCODE'=>'utf8',//编码
        'DB_PORT' => '3306', //端口
        'DB_PREFIX' => 'dmtx_' // 数据库表前缀
    )
);
 */

namespace Fanpaiji;

use PDO;

class M
{

    public $link; //数据库连接
    private $table; //表名
    private $prefix; //表前缀
    private $db_config; //数据库配置
    /**
     * 参数:表名 数据库配置数组 或 数据库配置文件路径
     * @param $table
     * @param string $db_config_arr_path
     */
    function __construct($table, $db_config_arr_path = 'config.php')
    {
        try {
            if (is_array($db_config_arr_path)) {
                $this->db_config = $db_config_arr_path;
            } else {
                $this->db_config = require($db_config_arr_path);
            }
            $this->conn();
            $this->table = $this->prefix . $table;
        } catch ( \Exception $exception ) {
            return $exception->getMessage();
        }
    }

    /**
     * 连接数据库
     */
    private function conn()
    {
        $db_config = $this->db_config;
        $host = $db_config["DB_CONFIG"]["DB_HOST"];
        $port = $db_config["DB_CONFIG"]["DB_PORT"];
        $user = $db_config["DB_CONFIG"]["DB_USER"];
        $pwd = $db_config["DB_CONFIG"]["DB_PWD"];
        $db_name = $db_config["DB_CONFIG"]["DB_NAME"];
        $db_encode = $db_config["DB_CONFIG"]["DB_ENCODE"];
        $this->prefix = $db_config["DB_CONFIG"]["DB_PREFIX"];

        try{
            $this->link = new PDO("mysql:host=$host;port=$port;dbname=$db_name",$user,$pwd,array(PDO::MYSQL_ATTR_INIT_COMMAND=>"set names '$db_encode'"));
        }catch (\PDOException $e){
//            throw new \Exception("数据库连接出错:".$e->getMessage());
            $this->link = "数据库连接出错:".$e->getMessage();
//            return "数据库连接出错:".$e->getMessage();
//            die("数据库连接出错:".$e->getMessage());
        }

    }

    public function _beginTransaction()
    {
        return $this->link->beginTransaction();
    }

    public function _commit()
    {
        return $this->link->commit();
    }

    public function _rollBack()
    {
        return $this->link->rollBack();
    }

    /**
     * 数据查询
     * 参数:sql条件(字符串 或 关联数组) 查询字段(字符串 或 数组) 使用的sql函数名
     * @param string $where
     * @param string $field
     * @param string $fun
     * @return array
     * 返回值:结果集 或 结果(出错返回空字符串)
     */
    public function select($where = '1', $field = "*", $fun = '')
    {
        $where = $this->toString($where);
        if(is_array($field))$field = implode(',', $field);
        $rarr = array();
        if (empty($fun)) {
            $sqlStr = "select $field from $this->table where $where";
             $rt =  $this->link->query($sqlStr);
            while ($rt && $arr = $rt->fetch(PDO::FETCH_ASSOC)) {
                array_push($rarr, $arr);
            }
        } else {
            $sqlStr = "select $fun($field) as rt from $this->table where $where";
            $rt = $this->link->query($sqlStr);
            $farr = $rt->fetch();
            $rarr = $farr["rt"];
        }
        return $rarr;
    }

    /**
     * 数据更新
     * 参数:sql条件(字符串 或 关联数组) 要更新的数据(字符串 或 关联数组)
     * @param $where
     * @param $data
     * @return bool
     * 返回值:语句执行成功或失败,执行成功并不意味着对数据库做出了影响
     */
    public function update($where, $data)
    {
        $where = $this->toString($where);
        $data = $this->toString($data,',');
        $sqlStr = "update $this->table set $data where $where";
        return $this->link->exec($sqlStr);
    }

    /**
     * 数据添加
     * 参数:数据(数组 或 关联数组 或 字符串) 无重复插入检查条件(字段数组，只有当$data为关联数组时才生效)
     * @param $data
     * @return int
     * 返回值:插入的数据的ID 或者 0
     */
    public function insert($data,$whereArr=array())
    {
        $field = '';
        $idata = '';
        if (is_array($data) && array_keys($data) != range(0, count($data) - 1)) {
            //关联数组
            while (list($k, $v) = each($data)) {
                if (empty($field)) {
                    $field = "`$k`";
                    $idata = "'$v'";
                } else {
                    $field .= ",`$k`";
                    $idata .= ",'$v'";
                }
            }
            if(count($whereArr))
            {
                $twhere = '';
                foreach ($data as $key => $value) {
                    if(in_array($key, $whereArr))
                    {
                        if($twhere=='')
                        {
                            $twhere = "$key = '$value'";
                        }else{
                            $twhere .= " and $key = '$value'";
                        }
                    }
                } 
                $tarr = $this->select($twhere);
                if (count($tarr)) {
                    return 0;
                }
            }
            
            $sqlStr = "insert into $this->table($field) values ($idata)";
        } else {
            //非关联数组 或字符串
            if (is_array($data)) {
                while (list($k, $v) = each($data)) {
                    if (empty($idata)) {
                        $idata = "'$v'";
                    } else {
                        $idata .= ",'$v'";
                    }
                }

            } else {
                //为字符串
                $idata = $data;
            }
            $sqlStr = "insert into $this->table values ($idata)";
        }
//        print_r($sqlStr);die();
     if($this->link->exec($sqlStr))
     {
         return $this->link->lastinsertid();
     }
        return 0;
    }

    /**
     * 数据删除
     * 参数:sql条件
     * @param $where
     * @return int
     */
    public function delete($where)
    {
        $sqlStr = "delete from $this->table where $where";
        return $this->link->exec($sqlStr);
    }
    /**
     * 数组转SQL条件字符串
     * @param  array $arr 
     * @param  string $sep 分隔符
     * @return string      
     */
    private function toString($arr,$sep='and')
    {
        if(!is_array($arr))return $arr;
        $str = '';
        foreach ($arr as $key => $value) {
            if($str)
            {
                $str .= " $sep $key = '$value'";
            }else{
                $str = "$key = '$value'";
            }
        }
        return $str;
    }

    /**
     * 关闭MySQL连接
     * @return bool
     */
//    public function close()
//    {
//        return mysql_close($this->link);
//    }

}


/*$hj= new M("user");
$arr = $hj->select("1","*","count");
print_r($arr);*/
//echo $hj->update("id=1","name='nnn'");

//echo $hj->insert(array("id"=>"NULL","name"=>"yyy"));
//echo $hj->delete("id>2");

/*$conArr = array(
    'DB_CONFIG' => array(
        //数据库配置
        'DB_HOST'=>'127.0.0.1',    //服务器地址
        'DB_NAME' => 'tmp', // 数据库名
        'DB_USER' => 'root', // 用户名
        'DB_PWD' => '', // 密码
        'DB_ENCODE'=>'utf8',//编码
        'DB_PORT' => '3306', //端口
        'DB_PREFIX' => 'dmtx_' // 数据库表前缀
    )
);
// $hj= new M("user",$conArr);
// print_r($hj->select());
// echo $hj->insert(array('id'=>'NULL','email'=>'bn@c.cc','password'=>'cde2'),array('email','password'));

$hj= new M("user",$conArr);
// $arr = $hj->select(array('id'=>'13'),array('email','password'));
// print_r($arr);
echo $hj->update(array('email'=>'qq@qq.com'),array('password'=>'2222vvvvvv','email'=>'xxxxxx@qq.com'));*/
